package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;
    @PostMapping
    public Result addDish(@RequestBody DishDTO dishDTO) {
        dishService.add(dishDTO);
        cleanCache("dish:"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    public Result page( DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult=dishService.page(dishPageQueryDTO);


        return Result.success(pageResult);
    }

    @DeleteMapping
    public Result deleteDish(@RequestParam List<Long> ids) {

        dishService.deleteBatch(ids);
        cleanCache("dish:*");
        return Result.success();

    }

    @GetMapping("/{id}")
    public Result getDish(@PathVariable Long id) {
        DishVO dishVO=dishService.getById(id);
        return Result.success(dishVO);
    }

    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);
        cleanCache("dish:*");//更新时候可能换分类 那么影响的就很多 直接简化处理
        return Result.success();
    }
    private void cleanCache(String pattern){

        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id) {
        dishService.startOrStop(status,id);

        cleanCache("dish:*");
        return Result.success();

    }
}
